

//客户端异步请求
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <fcntl.h>


char buff[1024];


int my_connet(char *ip, int port)  {

	int ret = -1;
	int fd = socket(AF_INET, SOCK_STREAM, 0);
	if(fd < 0)  {
		printf("socket error\n");
		return -1;
	}
	fcntl(fd, F_SETFL, O_NONBLOCK);

	struct sockaddr_in server_addr = {0};
	server_addr.sin_port = htons(port);
	server_addr.sin_family = AF_INET;
	//server_addr.sin_addr.s_addr = inet_addr(ip);
	inet_pton(AF_INET, ip, &server_addr.sin_addr);
	printf("connect.....\n");
	ret = connect(fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
	if(ret < 0) {
		printf("connetc error\n");
		return -2;
	}


	return fd;
}


void *my_recv(void *arg)
{
	struct epoll_event  events[100] = {0};
	int nready = 0;
	int i = 0;
	long epfd = (long)arg;
	int rsize = 0;

	while(1)  {
		nready = epoll_wait(epfd, events, 100, 0);
		if(nready < 0) 
			continue;

		//处理工作，可以用线程池

		for(i=0; i<nready; i++) {
			memset(buff, 0, sizeof(buff));
			rsize =	recv(events[nready].data.fd, buff, sizeof(buff), 0);
			if(rsize > 0)
				printf("recv -----  %s\n", buff);
			close(events[nready].data.fd);
		}

	}

	return NULL;
}


int my_close()
{

	//epoll_close();
}



int main(int argc, char **argv)
{
	int i = 0;
	int size = 0;
	int epfd = 0;
	pthread_t tid;

	if(argc != 3) {
		printf("main param error\n");
		return -1;
	}

	int port = atoi(argv[2]);

	epfd = epoll_create(1);
	if(epfd < 0)  {
		printf("epfd error\n");
		return -1;
	}


	//创建一个线程等待
	pthread_create(&tid, NULL, my_recv, epfd);


	printf("ip %s port %d\n", argv[1], port);
	for(i=0; i<100; i++) {
		int sockfd = my_connet(argv[1], port);
		if(sockfd <= 0) {
			printf("my_connet\n");
			return -1;
		}

		struct epoll_event  event = {0};
		event.data.fd = sockfd;
		event.events = EPOLLIN;
		epoll_ctl(epfd, EPOLL_CTL_ADD, sockfd, &event);


		snprintf(buff, sizeof(buff), "hello world %d\n", sockfd);
		printf("send ... %s\n", buff);

		send(sockfd, buff, strlen(buff), 0);
	}
	

	while(1);
	return 0;
}





